package com.example.blogdemo.controller;

import com.example.blogdemo.entity.HostHolder;
import com.example.blogdemo.entity.User;
import com.example.blogdemo.repository.UserRepository;
import com.example.blogdemo.util.FileUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author Anita
 * @Date 2018/1/3 9:43
 */
@Controller
@Slf4j
public class FileController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public String goUploadImg() {
        //跳转到 templates 目录下的 uploadimg.html
        return "upload";
    }

    @RequestMapping(value = "/uploadimg",method = RequestMethod.POST)
    public  String uploadImg(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        log.info("contentType+{}",contentType); //contentType+image/jpeg
        log.info("fileName+{}",fileName); //fileName+1F105134J8-10.jpg
//        String filePath = "D://笔记+练习//blogdemo//src//main//resources//static//img//";
        String filePath = "D://img//";
//        String filePath = "/Users/xuwanying/jishu/img/";
        User user = hostHolder.getUser();
        String url = "/images/"+fileName;
        User userGet = userRepository.findById(user.getId());
        userGet.setHeadUrl(url);
        userRepository.save(userGet);
        log.info("filePath+{}",filePath);  //filePath+D://img//
        try{
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
        return "redirect:/index";
    }

}






